<template>
  <div>
    <div class="mb-1">
      <a-checkbox v-model:checked="toggleExpand">展开/折叠</a-checkbox>
      <a-checkbox v-model:checked="toggleCheckAll">全选/全不选</a-checkbox>
    </div>
    <div class="border border-solid rounded-md border-gray-200 p-2">
      <a-skeleton active :loading="loading" :paragraph="{ rows: 5 }">
        <a-tree
          v-if="treeData && treeData.length > 0"
          v-model:checked-keys="checkedKeys"
          v-model:expanded-keys="expandedKeys"
          checkable
          :field-names="{ title: 'menuName', key: 'menuId' }"
          :tree-data="treeData"
        />
      </a-skeleton>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch, nextTick } from "vue";
import { MenuTreeItem } from "/@/api/home/menu/models";
import { getMenuTreeData } from "/@/api/home/menu";
import { loopItem } from "/@/utils/treeData";

const props = defineProps<{
  value: number[] | null;
}>();

const emits = defineEmits(["change"]);

const toggleExpand = ref(false);
const toggleCheckAll = ref(false);
const checkedKeys = ref<number[]>([]);
const expandedKeys = ref<number[]>([]);
const loading = ref(true);
const treeData = ref<MenuTreeItem[]>([]);
onMounted(async () => {
  const data = await getMenuTreeData();
  loading.value = false;
  if (data) {
    treeData.value = data;
  }
});

watch(toggleExpand, (v) => {
  if (v) {
    const keys: number[] = [];
    loopItem(treeData.value, (item) => {
      if (item.children && item.children.length > 0) {
        keys.push(item.menuId);
      }
    });
    expandedKeys.value = keys;
  } else {
    expandedKeys.value = [];
  }
});

watch(toggleCheckAll, (v) => {
  if (v) {
    const keys: number[] = [];
    loopItem(treeData.value, (item) => {
      keys.push(item.menuId);
    });
    checkedKeys.value = keys;
  } else {
    checkedKeys.value = [];
  }
});

watch(
  () => props.value,
  (v) => {
    isTriggerCheckedKeysWatch = false;
    checkedKeys.value = v || [];
    if (!v || v.length === 0) {
      toggleCheckAll.value = false;
    }
    nextTick(() => {
      isTriggerCheckedKeysWatch = true;
    });
  }
);

let isTriggerCheckedKeysWatch = true;
watch(checkedKeys, (v) => {
  if (!isTriggerCheckedKeysWatch) return;
  console.log(v);
  emits("change", v);
});
</script>
